import 'package:flutter/material.dart';
import 'package:network_info_plus/network_info_plus.dart';
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';

// 创建 StatefulWidget 类型的 NetworkScannerPage
class NetworkScannerPage extends StatefulWidget {
  const NetworkScannerPage({super.key});

  @override
  _NetworkScannerPageState createState() => _NetworkScannerPageState();
}

// _NetworkScannerPageState 类管理 NetworkScannerPage 的状态
class _NetworkScannerPageState extends State<NetworkScannerPage> {
  final List<String> _foundDevices = [];
  final _networkInfo = NetworkInfo();

  @override
  void initState() {
    super.initState();
    _checkPermissionsAndScan();
  }

  Future<void> _checkPermissionsAndScan() async {
    // 请求必要的权限
    Map<Permission, PermissionStatus> statuses = await [
      Permission.locationWhenInUse,
      Permission.accessMediaLocation,
    ].request();

    if (statuses[Permission.locationWhenInUse]!.isGranted) {
      discoverDevices();
    } else {
      // 显示权限被拒绝的提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('需要位置权限来扫描网络设备')),
        );
      }
    }
  }

  Future<void> discoverDevices() async {
    final wifiIP = await _networkInfo.getWifiIP();
    if (wifiIP == null) return;
    
    final subnet = wifiIP.substring(0, wifiIP.lastIndexOf('.'));
    
    for (var i = 1; i < 255; i++) {
      final host = '$subnet.$i';
      try {
        final result = await InternetAddress.lookup(host);
        if (result.isNotEmpty) {
          setState(() {
            _foundDevices.add(host);
          });
        }
      } catch (e) {
        // 设备未响应
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('网络设备扫描'),  // 应用栏标题
        ),
        body: ListView.builder(
          itemCount: _foundDevices.length,  // 列表项数等于发现的设备数
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(_foundDevices[index]),  // 列表项标题显示设备的IP地址
            );
          },
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();  // 组件销毁时执行的操作
  }
}